var initScreen=function(callback){
    //$("html").css("font-size",document.documentElement.clientHeight/document.documentElement.clientWidth<1.5 ? (document.documentElement.clientHeight/603*312.5+"%") : (document.documentElement.clientWidth/375*312.5+"%")); //单屏全屏布局时使用,短屏下自动缩放
    $("html").css("font-size",document.documentElement.clientWidth/375*312.5+"%");
    if(callback)callback();
}

function _onorientationchange(e){
    if(window.orientation==90||window.orientation==-90){
    	//横版
        $("#forhorview").css("display", "-webkit-box");
        $("#wrap").hide();
    }else{
    	//竖屏
    	var st=setTimeout(initScreen,300);
        $("#forhorview").css("display", "none");
        $("#wrap").show();
    }
}

window.addEventListener("onorientationchange" in window ? "orientationchange" : "resize",function(e){
	_onorientationchange(e);
}, false);

$(function(){
	_onorientationchange();
	initScreen();

	$(".page").height($(window).height())

	var manifest = []

	var manifest2 = []

	$("#manifest img").each(function(idx,item){
		manifest.push($(item).data("src"));
	})
	
	$("#manifest2 img").each(function(idx,item){
		manifest2.push($(item).data("src"));
	})
	
	var voice;
	var group = [];
	$("#group img").each(function(idx,item){
		group.push($(item).data("src"));
	})
    if(/micromessenger/i.test(navigator.userAgent.toLowerCase())){
        document.addEventListener("WeixinJSBridgeReady", function () {
            WeixinJSBridge.invoke('getNetworkType', {}, function (e) {
                voice = audio.create({
                    audio: group,
                    autoPlay: false,
                    loop: false,
                    playAll: false,
                    end: function(cur, length) {
                    	if(cur==2){
		            		voice.toPlay(3);
		            	}
                    }
                });
            });
        }, false);

    }else{
        voice = audio.create({
            audio: group,
            autoPlay: false,
            loop: false,
            playAll: false,
            end: function(cur, length) {
            	if(cur==2){
            		voice.toPlay(3);
            	}
            }
        });
    }


	function Page(){
        this.init();
    }

	Page.prototype = {
		curPage: 1,
		works: "",
		fuliSwiper: null,
		isPause: false,
		init: function(){
			this.loadSource();
			this.bind();
    	},
		loadSource: function(){
			var that = this;
			var loader = new createjs.LoadQueue(true);
			loader.installPlugin(createjs.Sound);
		    loader.on("complete", that.loadComplete,this);
		    loader.on("progress", that.onProgress);
		    loader.loadManifest(manifest);
		},
		onProgress: function(e){
			var percent = Math.ceil(e.progress*100)+"%";
			$(".percent").html(percent)
		},
		loadComplete: function(){
			$("#loading").hide();
			$(".msg-box").addClass("show");
			voice.toPlay(1);
			var midx = 6;
			var len = $(".msg").length;
			var msgInter = setInterval(function(){
					if(midx<0){
						clearInterval(msgInter);
						return;
					}
					$(".msg").eq(midx).addClass("show");
					midx--;
				},400);

			var that = this;
			var loader2 = new createjs.LoadQueue(true);
		    loader2.loadManifest(manifest2);
		},
		bind: function(){
			this.bindShare();
			this.bindMenu();
			this.bindFuli();
			this.bindRule();
			this.bindClose();
			this.bindFile();
			this.bindReUpload();
			this.bindPingxuan();
			this.bindForm();
			this.bindReplay();
			this.bindStart();
			this.bindMusic();
		},
        autoSwiper : function(timer,node){
            var self = this;

            setTimeout(function(){
                self.matchSwiper.slideNext();
                node = node.next();
                if(node.length != 0){
                    var timer = node.attr('data-swiper-autoplay') - 0;
                    if(timer){
                        self.autoSwiper(timer,node)
                    }
                }
            },timer);
        },
		bindStart: function(){
			var that = this;
			var index = 0;
			var winH = $(window).height();
			
			$(".msg")[0].addEventListener("webkitAnimationEnd", function(){
				var len = $(".list>div").length
				$(".page-1").hide();
				$(".page-2").show();
				that.curPage = 2;
				voice.toPlay(2);
				var showMsg = setInterval(function(){
					if(index==len){
						clearInterval(showMsg);
						setTimeout(function(){
							$(".page-2").hide();
							$(".page-3").show();
							that.renderMatch()
							that.curPage = 3;
							if(!that.isPause){
								voice.toPlay(3);
							}
						},1000);
						
						return;
					}
					//voice.toPlay(2);
					if($(".list>div").eq(index).hasClass("time")){
						$(".list>div").eq(index).show();
						$(".list>div").eq(index).next().show();
						index++
					}else{
						$($(".list>div")[index]).show();
					}
					if($('.list')[0].scrollHeight>$(window).height()-100){
						$("html,body").height('auto');
					}
					$('html,body').scrollTop($('.list')[0].scrollHeight);
					index++
				},1300)
			},false)
		},
		renderMatch: function(){
			var that = this;
			this.matchSwiper = new Swiper ('#matchSwiper',{
				direction: "vertical",
				resistanceRatio: 0,
    			onSlideChangeStart: function(swiper){
    				var index = swiper.activeIndex
    				if(index==1){
    					setTimeout(function(){
    						swiper.slideNext(false,0);
    					},2000)
    					setTimeout(function(){
    						swiper.slideTo(3,0);
    					},6700)
    				}
    				if(index==3){
    					$(".view").click();
    				}
    			},
    			onReachEnd: function(swiper){
    			}
		  	})
		},
		bindMenu: function(){
			$(".menu").click(function(){
		      	$(this).parent().toggleClass("show");
		    });
		},
		bindFuli: function(){
			var that = this;
			$(".fuli").click(function(){
				$("#fuli-box").show();
				setTimeout(function(){
					$("#fuli-box").addClass("show");
				},100);
				if(!that.fuliSwiper){
					that.fuliSwiper = new Swiper ('#fuliSwiper',{
						nextButton: '.swiper-button-next',
		    			prevButton: '.swiper-button-prev'
				  	})
				}
			})
		},
		bindRule: function(){
			$(".view").click(function(){
				$("#rule-box").show();
				setTimeout(function(){
					$("#rule-box").addClass("show");
				},100);
			})
		},
		bindClose: function(){
			$(".close").click(function(){
				var pop = $(this).parents(".pop");
		   		pop.removeClass("show");
				setTimeout(function(){
					pop.hide();
				},300);
			})
		},
		bindFile: function(){
    		var that = this;
    		$(".fileinput").change(function(){
    			var file = this.files[0];
    			that.readFile(file);
    		})
    	},
    	readFile: function(file){
    		var that = this;
    		var reader = new FileReader();
    		switch (file.type){
				case 'image/jpg':
				case 'image/png':
				case 'image/jpeg':
					reader.readAsDataURL(file);
					reader.addEventListener('load',function (e) {
						//$(".preview").attr("src",reader.result)
						$(".preview-box").css({
							background: 'url('+reader.result+')',
							backgroundSize: 'cover !important',
							backgroundPosition: 'center center'
						})
						$(".page-3").hide();
						$(".page-5").show();
						that.curPage = 5;
						that.works = reader.result
					})
					break;
				default:
					layer.open({
						content: "请上传图片",
						shadeClose: false,
						time: 1,
						className: "layer-alert"
					})
			}
    	},
    	bindReUpload: function(){
    		var that = this;
    		$(".reupload").click(function(){
    			$(".page-5").hide();
    			$(".page-3").show();
    			that.curPage = 3;
    		})
    	},
    	bindPingxuan: function(){
    		var that = this;
    		$(".pingxuan").click(function(){
				$(".page-5").hide();
				$(".page-6").show();
				that.curPage = 6;
    		});
    	},
		bindForm: function(){
			var that = this;
			$(".subForm").click(function(){
				var username = $.trim($("#username").val());
				var phone = $.trim($("#phone").val());
				var pname = $.trim($("#pname").val());
				if(username==""){
					layer.open({
						content: "请填写厨师大名",
						shadeClose: false,
						time: 1,
						className: "layer-alert"
					})
					return;
				}
				if(phone==""){
					layer.open({
						content: "请填写手机号码",
						shadeClose: false,
						time: 1,
						className: "layer-alert"
					})
					return;
				}
				if (!/^1[34578]\d{9}/.test(phone)) {
					layer.open({
						content: "请输入正确的手机号码",
						shadeClose: false,
						time: 1,
						className: "layer-alert"
					})
					return;
				}
				if(pname==""){
					layer.open({
						content: "请填写作品名称",
						shadeClose: false,
						time: 1,
						className: "layer-alert"
					})
					return;
				}
				var zhuliao = $("#zhuliao").val();
    			var fuliao = $("#fuliao").val();
    			var zuofa = $("#zuofa").val();
    			layer.open({
				    type: 2,
				    shadeClose: false,
				    content: '提交中'
			  	});
				$.ajax({
					type:"post",
					url:"http://www.huihaicenter.com/api/lijinji/api.php?action=data",
					dataType: "json",
					data: {
						zhuliao: zhuliao,
						fuliao: fuliao,
						zuofa: zuofa,
						imgs: that.works,
						realname: username,
						phone: phone,
						workname: pname
					},
					success: function(res){
						layer.closeAll();
						if(res.status=="success"){
							$(".page-6").hide();
							$(".page-7").show();
							that.curPage = 7;
						}else{
							layer.open({
								content: res.msg,
								shadeClose: false,
								time: 1,
								className: "layer-alert"
							})
						}
					}
				});
			});
		},
		bindReplay: function(){
			var that = this;
			$(".replay").click(function(){
				$(".page-7").hide();
				$(".page-3").show();
				that.curPage = 3;
			})
		},
		bindShare: function(){
			$(".share").click(function(){
				$(".share-box").show();
				setTimeout(function(){
					$(".share-box").addClass("show");
				},100);
			});

			$(".share-box").click(function(){
				$(".share-box").removeClass("show");
				setTimeout(function(){
					$(".share-box").hide();
				},300);
			})
		},
		bindMusic: function(){
			var that = this;
			$(".music").click(function(){
				if($(this).hasClass("play")){
					$(".music").removeClass("play");
					that.isPause = true;
					voice.pause();
				}else{
					$(".music").addClass("play");
					that.isPause = false;
					if(that.curPage>2){
						voice.toPlay(3)
					}else{
						voice.toPlay(2)
					}
				}
			})
		}
	}

	new Page();

	wx.config(wx_config);
	var src = window.location.href;
	var imgUrl = 'http://www.huihaicenter.com/www/projects/ljj/'+$("#sharePic").attr("src");
	var random = Math.round(Math.random());
	wx.ready(function(){
		var shareMeta1 = {
			title: '【美食小当家】这封关于美食的战书你敢不敢打开~',
		    desc: '美食小当家纷纷出战，就等你来会一会！',
		    link: src,
		    imgUrl: imgUrl
		}
		var shareMeta2 = {
			title: '【您收到姐妹的菜】马上接收~',
		    desc: '每个都是天然、严选、健康！',
		    link: src,
		    imgUrl: imgUrl
		}
		var shareMetaTimeline1 = {
			title: '【美食小当家】这封关于美食的战书你敢不敢打开~',
			link: src,
			imgUrl: imgUrl
		}
		var shareMetaTimeline2 = {
			title: '深夜，你的姐妹送你很多……',
			link: src,
			imgUrl: imgUrl
		}
		//var shareMeta = random==0?shareMeta1:shareMeta2;
		//var shareMetaTimeline = random==0?shareMetaTimeline1:shareMetaTimeline1;

		//分享到朋友圈
		wx.onMenuShareTimeline($.extend(shareMetaTimeline1,{
			success: function () {
		        _czc.push(﻿['_trackEvent', 'share', '分享到朋友圈']);
		    }
		}));

		//分享给朋友
		wx.onMenuShareAppMessage($.extend(shareMeta1,{
			success: function () {
		        _czc.push(﻿['_trackEvent', 'share', '分享给好友']);
		    }
		}));
	});
});
